<template>
  <div class="approval-center-container">
    <el-card>
      <div slot="header">
        <span>审批中心</span>
      </div>
      
      <!-- Tab切换 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="待办任务" name="tasks">
          <template slot="label">
            <span>
              <i class="el-icon-s-order"></i>
              待办任务
              <el-badge v-if="taskCount > 0" :value="taskCount" class="tab-badge" />
            </span>
          </template>
          
          <!-- 待办任务表格 -->
          <el-table :data="tasks" style="width: 100%" v-loading="tasksLoading">
            <el-table-column prop="instance.id" label="ID" width="80" />
            <el-table-column prop="instance.title" label="标题" show-overflow-tooltip />
            <el-table-column prop="instance.processName" label="流程名称" width="150" />
            <el-table-column prop="instance.applicantName" label="申请人" width="120" />
            <el-table-column prop="task.taskName" label="当前节点" width="150" />
            <el-table-column prop="task.createTime" label="到达时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.task.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" @click="handleTask(scope.row)">处理</el-button>
                <el-button type="text" @click="viewDetail(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="我的申请" name="applications">
          <template slot="label">
            <span>
              <i class="el-icon-document"></i>
              我的申请
              <el-badge v-if="applicationCount > 0" :value="applicationCount" class="tab-badge" />
            </span>
          </template>
          
          <!-- 我的申请表格 -->
          <el-table :data="applications" style="width: 100%" v-loading="applicationsLoading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="title" label="标题" show-overflow-tooltip />
            <el-table-column prop="processName" label="流程名称" width="150" />
            <el-table-column prop="status" label="状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="currentNode" label="当前节点" width="150" />
            <el-table-column prop="startTime" label="发起时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.startTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" @click="viewDetail(scope.row)">查看详情</el-button>
                <el-button
                  v-if="scope.row.status === 'PENDING'"
                  type="text"
                  style="color: #F56C6C;"
                  @click="cancelApproval(scope.row)"
                >
                  撤销
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="已办任务" name="completed">
          <template slot="label">
            <span>
              <i class="el-icon-circle-check"></i>
              已办任务
              <el-badge v-if="completedCount > 0" :value="completedCount" class="tab-badge" />
            </span>
          </template>
          
          <!-- 已办任务表格 -->
          <el-table :data="completedTasks" style="width: 100%" v-loading="completedLoading">
            <el-table-column prop="instance.id" label="ID" width="80" />
            <el-table-column prop="instance.title" label="标题" show-overflow-tooltip />
            <el-table-column prop="instance.processName" label="流程名称" width="150" />
            <el-table-column prop="instance.applicantName" label="申请人" width="120" />
            <el-table-column prop="task.taskName" label="节点" width="150" />
            <el-table-column prop="task.status" label="处理结果" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.task.status === 'APPROVED' ? 'success' : 'danger'">
                  {{ scope.row.task.status === 'APPROVED' ? '同意' : '拒绝' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="task.comment" label="审批意见" show-overflow-tooltip />
            <el-table-column prop="task.completeTime" label="处理时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.task.completeTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" @click="viewDetail(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 处理任务对话框 -->
    <el-dialog title="处理审批" :visible.sync="showTaskDialog" width="600px">
      <div v-if="currentTask.instance" class="task-info">
        <h4>{{ currentTask.instance.title }}</h4>
        <p><strong>流程名称：</strong>{{ currentTask.instance.processName }}</p>
        <p><strong>申请人：</strong>{{ currentTask.instance.applicantName }}</p>
        <p><strong>当前节点：</strong>{{ currentTask.task.taskName }}</p>
        <p><strong>到达时间：</strong>{{ formatDate(currentTask.task.createTime) }}</p>
      </div>
      
      <div v-if="formDataObj && Object.keys(formDataObj).length > 0" class="form-data">
        <h4>申请内容</h4>
        <div class="form-data-content">
          <div v-for="(value, key) in formDataObj" :key="key" class="form-item">
            <strong>{{ key }}：</strong>{{ value }}
          </div>
        </div>
      </div>
      
      <el-form :model="taskForm" label-width="100px">
        <el-form-item label="审批意见">
          <el-input
            v-model="taskForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTaskDialog = false">取消</el-button>
        <el-button type="success" @click="handleApprove">同意</el-button>
        <el-button type="danger" @click="handleReject">拒绝</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMyTasks, getMyApplications, getMyCompletedTasks, completeTask, cancelInstance } from '@/api/approval'

export default {
  name: 'ApprovalCenter',
  
  data() {
    return {
      activeTab: 'tasks',
      tasks: [],
      applications: [],
      completedTasks: [],
      tasksLoading: false,
      applicationsLoading: false,
      completedLoading: false,
      taskCount: 0,
      applicationCount: 0,
      completedCount: 0,
      showTaskDialog: false,
      currentTask: {},
      taskForm: {
        comment: ''
      }
    }
  },
  
  computed: {
    formDataObj() {
      if (this.currentTask.instance && this.currentTask.instance.formData) {
        try {
          return JSON.parse(this.currentTask.instance.formData)
        } catch (e) {
          return {}
        }
      }
      return {}
    }
  },
  
  created() {
    this.loadAllData()
    
    // 根据URL参数设置默认tab
    if (this.$route.query.tab) {
      this.activeTab = this.$route.query.tab
    }
  },
  
  watch: {
    // 监听路由变化，保持tab状态
    '$route'(to, from) {
      if (to.query.tab && to.query.tab !== this.activeTab) {
        this.activeTab = to.query.tab
      }
    }
  },
  
  methods: {
    // 加载所有数据
    loadAllData() {
      this.loadTasks()
      this.loadApplications()
      this.loadCompletedTasks()
    },
    
    // 加载待办任务
    loadTasks() {
      this.tasksLoading = true
      getMyTasks().then(res => {
        this.tasks = res.data || []
        this.taskCount = this.tasks.length
        this.tasksLoading = false
      }).catch(() => {
        this.tasksLoading = false
      })
    },
    
    // 加载我的申请
    loadApplications() {
      this.applicationsLoading = true
      getMyApplications().then(res => {
        this.applications = res.data || []
        this.applicationCount = this.applications.length
        this.applicationsLoading = false
      }).catch(() => {
        this.applicationsLoading = false
      })
    },
    
    // 加载已办任务
    loadCompletedTasks() {
      this.completedLoading = true
      getMyCompletedTasks().then(res => {
        this.completedTasks = res.data || []
        this.completedCount = this.completedTasks.length
        this.completedLoading = false
      }).catch(() => {
        this.completedLoading = false
      })
    },
    
    // Tab切换处理
    handleTabClick(tab) {
      this.activeTab = tab.name
      // 可以根据需要在这里添加特定tab的数据加载逻辑
    },
    
    // 处理任务
    handleTask(row) {
      this.currentTask = row
      this.taskForm.comment = ''
      this.showTaskDialog = true
    },
    
    // 查看详情
    viewDetail(row) {
      if (row.instance) {
        this.$router.push({
          path: `/approval/detail/${row.instance.id}`,
          query: { 
            from: 'approval-center',
            tab: this.activeTab 
          }
        })
      } else {
        this.$router.push({
          path: `/approval/detail/${row.id}`,
          query: { 
            from: 'approval-center',
            tab: this.activeTab 
          }
        })
      }
    },
    
    // 撤销申请
    cancelApproval(row) {
      this.$confirm('确定要撤销这个申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelInstance(row.id).then(() => {
          this.$message.success('撤销成功')
          this.loadApplications()
        })
      })
    },
    
    // 同意审批
    handleApprove() {
      this.completeTask('approve')
    },
    
    // 拒绝审批
    handleReject() {
      if (!this.taskForm.comment) {
        this.$message.warning('拒绝时必须填写审批意见')
        return
      }
      this.completeTask('reject')
    },
    
    // 完成任务
    completeTask(action) {
      const data = {
        taskId: this.currentTask.task.id,
        action: action,
        comment: this.taskForm.comment
      }
      
      completeTask(data).then(() => {
        this.$message.success('处理成功')
        this.showTaskDialog = false
        this.loadTasks() // 重新加载待办任务
        this.loadCompletedTasks() // 重新加载已办任务
      })
    },
    
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'PENDING': '审批中',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝',
        'CANCELLED': '已撤销'
      }
      return statusMap[status] || status
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.approval-center-container {
  padding: 20px;
}

.tab-badge {
  margin-left: 8px;
}

.task-info {
  margin-bottom: 15px;
}

.task-info h4 {
  margin-bottom: 10px;
  color: #303133;
}

.task-info p {
  margin: 5px 0;
  color: #606266;
}

.form-data {
  margin-bottom: 20px;
}

.form-data h4 {
  margin-bottom: 10px;
  color: #303133;
}

.form-data-content {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.form-item {
  margin-bottom: 8px;
}

.form-item:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>
